#include "encodeutil.h"
using namespace std;
using namespace cocos2d;

std::string EncodeUtil::WStrToUTF8(const std::wstring& src){
  std::string result_str;
  for (size_t i = 0; i < src.size(); i++){
    wchar_t w = src[i];
    if (w <= 0x7f) {
      result_str.push_back((char)w);
    } else if (w <= 0x7ff){
      result_str.push_back(0xc0 | ((w >> 6)& 0x1f));
      result_str.push_back(0x80| (w & 0x3f));
    } else if (w <= 0xffff){
      result_str.push_back(0xe0 | ((w >> 12)& 0x0f));
      result_str.push_back(0x80| ((w >> 6) & 0x3f));
      result_str.push_back(0x80| (w & 0x3f));
    } else if (sizeof(wchar_t) > 2 && w <= 0x10ffff){
      result_str.push_back(0xf0 | ((w >> 18) & 0x07));
      result_str.push_back(0x80| ((w >> 12) & 0x3f));
      result_str.push_back(0x80| ((w >> 6) & 0x3f));
      result_str.push_back(0x80| (w & 0x3f));
    } else {
      result_str.push_back('?');
    }
  }
  return result_str;
}